#include "NetMessenger.h"

void NetMessenger::TickToService()
{
    if (!m_Client.IsConnected())
    {
        if (!m_Client.Connect(serviceIP, servicePort))
        {
            return;
        }
        else
        {
            m_Client.RegisterFunction(std::bind(&NetMessenger::HandleServiceMsg, this, std::placeholders::_1, std::placeholders::_2));
        }
    }
    m_Client.Tick();
    if (!m_reqMessage.Empty())
    {
        NetMessage msg;
        if (m_reqMessage.TryPop(msg))
        {
            json obj;
            obj["sender"] = msg.sender;
            obj["data"] = msg.data;
            m_Client.SendParams("handle_msg_from_messenger", obj);
        }
    }
}

void NetMessenger::HandleServiceMsg(SOCKET s, const std::string &data)
{
    m_rpcHandler.Dispatch(s, data);
}

void NetMessenger::TickToClient()
{
    if (!m_rspMessage.Empty())
    {
        NetMessage msg;
        if (m_rspMessage.TryPop(msg))
        {
            this->SendParams(msg.receiver, msg.data);
        }
    }
}

void NetMessenger::HandleClientMsg(SOCKET s, const std::string &data)
{
    NetMessage msg;
    msg.sender = s;
    msg.data = data;
    m_reqMessage.Push(msg);
}
